<template>
  <div class="app-container">
    <div class="head-container">
      <label class="el-form-item-label">商品名称</label>
      <el-input v-model="query.name" clearable placeholder="商品名称" style="width: 185px;" class="filter-item" @keyup.enter.native="queryShopItems" />
      <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="queryShopItems">搜索</el-button>
    </div>
    <!--表单组件-->
    <el-dialog :close-on-click-modal="false" :visible.sync="dialog" title="订单信息" width="800px">
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
        <el-form-item label="商品名称" prop="name">
          <span>{{ form.name }}</span>
        </el-form-item>
        <el-form-item label="单  价" prop="price">
          <span>{{ form.price }}</span>
        </el-form-item>
        <el-form-item label="使用次数" prop="orderTotalCount">
          <span>{{ form.orderTotalCount }}</span>
        </el-form-item>
        <el-form-item label="购买数量" prop="itemAmount">
          <el-input-number v-if="form.orderId == null || form.orderId === ''" v-model="form.itemAmount" :min="1" :max="100" controls-position="right" style="width: 370px;" @change="itemAmountChange" />
          <span v-if="form.orderId != null && form.orderId != ''">{{ form.itemAmount }}</span>
        </el-form-item>
        <el-form-item label="订单金额" prop="amount">
          <span>{{ form.amount }}</span>
        </el-form-item>
        <el-form-item label="留  言" prop="orderMemo">
          <el-input v-if="form.orderId == null || form.orderId === ''" v-model="form.orderMemo" :rows="3" type="textarea" style="width: 370px;" />
          <span v-if="form.orderId != null && form.orderId != ''">{{ form.orderMemo }}</span>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button v-if="form.orderId == null || form.orderId === ''" type="text" @click="cancelDialog">取消</el-button>
        <el-button v-if="form.orderId == null || form.orderId === ''" type="primary" :loading="formLoading" @click="addOrder">生成订单</el-button>
        <el-button v-if="form.orderId != null && form.orderId != '' && form.status === 'CREATED' " type="primary" :loading="formLoading" @click="payOrder">支付</el-button>
        <!-- <el-button :loading="crud.cu === 2" type="primary" @click="submitOrder">确认</el-button> -->
        <el-button v-if="form.orderId != null && form.orderId != '' && form.status === 'PAYING' " type="primary" :loading="formLoading" @click="toMyOrder">我已完成支付</el-button>
        <el-button v-if="form.orderId != null && form.orderId != '' && form.status === 'PAYING' " type="primary" :loading="formLoading" @click="toMyOrder">查看订单</el-button>

      </div>
    </el-dialog>
    <el-row>
      <el-col v-for="(o, index) in data" :key="o.itemId" :span="8" :offset="index > 0 ? 2 : 0">
        <el-card :body-style="{ padding: '0px' }">
          <div style="padding: 14px;">
            <span>{{ o.name }}</span>
          </div>
          <img src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png" class="image">
          <div style="padding: 14px;">
            <span>{{ o.memo }}</span>
            <div class="bottom clearfix">
              <el-button type="text" class="button" @click="openDialog(o)">购买</el-button>

            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import crudItem from '@/api/shop/shop'
// import CRUD, { presenter, header, form, crud } from '@crud/crud'
const defaultForm = { orderId: null, itemId: null, name: null, price: null, orderMemo: null, orderTotalCount: null, leftCount: null, status: null, amount: 0, itemAmount: 0 }
export default {
  name: 'Home',
  /* mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '商品', url: 'api/shop/item', idField: 'itemId', sort: 'itemId,desc', crudMethod: { ...crudItem }})
  },*/
  rules: { },
  data() {
    return {
      rules: {},
      queryTypeOptions: [
        { key: 'name', display_name: '商品名称' }
      ],
      page: {
        // 页码
        page: 0,
        size: 10,
        total: 0
      },
      data: [],
      params: {},
      // sort: null,
      query: {
        name: ''
      },
      sort: ['createTime,desc'],
      form: Object.assign({}, defaultForm),
      // 整体loading
      loading: false,
      dialog: false,
      formLoading: false,
      // 支付窗口
      payUrl: '',
      payWin: null
    }
  },
  watch: {
    payUrl(newVal, oldVal) {
      if (newVal && this.payWin) {
        this.payWin.sessionStorage.clear()
        this.payWin.location.href = newVal
        // 重定向后把url和newWin重置
        this.payUrl = ''
        this.payWin = null
      }
    }
  },
  created() {
    this.page.page = 1
    this.init()
  },
  methods: {
    addOrder() {
      this.formLoading = true
      crudItem.add(this.form).then(data => {
        this.form.orderId = data.orderId
        this.form.status = data.status
        this.$notify({
          title: '订单创建成功',
          type: 'success',
          duration: 2500
        })
        this.formLoading = false
      }).catch(err => {
        this.formLoading = false
        this.$notify({
          title: '订单创建失败' + err.response.data.message,
          type: 'error',
          duration: 5000
        })
      })
    },
    payOrder() {
      this.formLoading = true
      this.payWin = window.open()
      let url = ''
      if (/(Android)/i.test(navigator.userAgent)) { // 判断是否为Android手机
        url = 'asWeb'
      } else if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) { // 判断是否为苹果手机
        url = 'asWeb'
      } else {
        url = 'asPc'
      }
      crudItem.pay(url, this.form).then(res => {
        this.formLoading = false
        this.payUrl = res
        this.form.status = 'PAYING'
      }).catch(err => {
        this.formLoading = false
        console.log(err.response.data.message)
        this.$notify({
          title: '订单支付失败' + err.response.data.message,
          type: 'error',
          duration: 5000
        })
      })
    },
    payOrder1() {
      this.formLoading = true
      crudItem.pay(this.form).then(data => {
        this.form.orderId = data.orderId
        this.form.status = data.status
        this.$notify({
          title: '订单支付成功',
          type: 'success',
          duration: 2500
        })
        this.formLoading = false
      }).catch(err => {
        this.formLoading = false
        this.$notify({
          title: '订单支付失败' + err.response.data.message,
          type: 'error',
          duration: 5000
        })
      })
    },
    toMyOrder() {
      this.$router.push({ path: '/service/order' })
    },
    cancelDialog() {
      this.dialog = false
      this.form = Object.assign({}, defaultForm)
    },
    openDialog(data) {
      var val = Object.assign({}, data)
      val.amount = val.price
      val.itemAmount = 1
      val.orderTotalCount = val.totalCount
      val.orderMemo = ''
      this.form = val
      this.dialog = true
    },
    queryShopItems() {
      this.init()
    },
    getQueryParams() {
      return {
        page: this.page.page - 1,
        size: this.page.size,
        sort: this.sort,
        ...this.query
      }
    },
    async init() {
      return new Promise((resolve, reject) => {
        this.loading = true
        crudItem.query(this.getQueryParams()).then(data => {
          this.total = data.totalElements
          this.data = data.content
          // time 毫秒后显示表格
          setTimeout(() => {
            this.loading = false
          }, this.time)
          resolve(data)
        }).catch(err => {
          this.loading = false
          reject(err)
        })
      })
    },
    itemAmountChange() {
      var form = this.form
      form.amount = (form.itemAmount * form.price).toFixed(2)
      form.orderTotalCount = form.totalCount * form.itemAmount
    }/*,
    [CRUD.HOOK.afterRefresh]() {
      this.crud.data.forEach(val => {

      })
    }*/
  }
}
</script>

<style>
    .time {
      font-size: 13px;
      color: #999;
    }

    .bottom {
      margin-top: 13px;
      line-height: 12px;
    }

    .button {
      //padding: 0;
      padding-right: 40px;
      float: right;
    }

    .image {
      width: 100%;
      display: block;
    }

    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }

    .clearfix:after {
        clear: both
    }
</style>
